package com.question.service.impl;

import com.question.constant.MessageConstant;
import com.question.context.BaseContext;
import com.question.exception.CommentNotExistException;
import com.question.mapper.CommentLikeMapper;
import com.question.mapper.CommentMapper;
import com.question.pojo.entity.Comment;
import com.question.pojo.entity.CommentLike;
import com.question.pojo.vo.CommentLikeVO;
import com.question.service.CommentLikeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class CommentLikeServiceImpl implements CommentLikeService {

    @Autowired
    private CommentLikeMapper commentLikeMapper;
    @Autowired
    private CommentMapper commentMapper;

    /**
     * 评论添加取消点赞
     * @param commentId
     */
    public void likeOrUnlikeComment(Integer commentId) {
        CommentLike commentLike = CommentLike.builder()
                .commentId(commentId)
                .userId(BaseContext.getCurrentId().intValue())
                .build();

        // 判断评论是否存在
        Comment comment = commentMapper.findCommentById(commentId);
        if (comment == null) {
            throw new CommentNotExistException(MessageConstant.COMMENT_NOT_EXISTS);
        }

        // 判断用户是否点赞评论
        Boolean isLike = commentLikeMapper.selectByCommentIdAndUserId(commentLike);

        if (isLike == null ) {
            // 添加点赞
            commentLikeMapper.insert(commentLike);
        } else {
            // 取消点赞
            commentLikeMapper.deleteByUserIdAndQuestionId(commentLike);
        }
    }

    /**
     * 获取评论点赞数
     * @param questionId
     * @return
     */
    public List<CommentLikeVO> getCommentLikeCount(Integer questionId) {
        List<CommentLikeVO> commentLikeList = commentLikeMapper.getCommentLikeCount(questionId);
        return commentLikeList;
    }

    /**
     * 获取当前用户点赞评论列表
     * @param questionId
     * @return
     */
    public List<Integer> getCommentLikeListByUserId(Integer questionId) {
        return commentLikeMapper.getCommentLikeListByUserId(questionId, BaseContext.getCurrentId().intValue());
    }
}
